var express = require('express');
var router = express.Router();
var User = require('../../modules/system/user');
var Page = require('../../utils/page/Page');
var MD5 = require('../../utils/secure/MD5');
var UserService = require('../../service/system/UserService');

var service = new UserService();

router.route('/users')
    .get(function(req, res) {
        //查询所有
        var user = new User(req.query);
        var query = new Page({
            start : req.query.start,
            limit : req.query.limit,
            conditionObj : user
        });
        service.findPage(query,function(err,page){
            res.json(page);
        });
    })
    .post(function(req, res) {
        //增加
        var user = new User(req.body);

        var arr = req.body.department.split('=');
        user.department._id = arr[0];
        user.department.departmentName = arr[1];

        user.password = MD5.encrypt('test');
        user.status = 1;

        service.save(user,function(err){
            if (err) {
                res.send({ success:false,'info':err});
            }

            res.send({ success:true,'info':'保存成功'});
        });
    });
router.route('/users/:id')
    .get(function(req, res) {
        //根据ID查询
        service.getById(req.params.id,function(err,page){
            if (err) {
                res.send({ success:false,'info':err});
            }
            res.json(page);
        });
    })
    .put(function(req,res) {
        var arr = req.body.department.split('=');
        var department = {
            _id : arr[0],
            departmentName : arr[1]
        };
        req.body.department = department;
        //根据ID修改
        service.updateById(req.params.id, req.body, function (err) {
            if (err) {
                res.send({ success: false, 'info': err});
            }
            res.send({ success: true, 'info': '修改成功'});
        });
    });

module.exports = router;